from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class User(db.Model):
    """用户表"""
    __tablename__ = 'user'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='用户ID')
    phone = db.Column(db.String(20), unique=True, nullable=False, comment='手机号')
    password = db.Column(db.String(100), nullable=False, comment='密码（加密）')
    nickname = db.Column(db.String(50), nullable=True, comment='昵称')
    avatar = db.Column(db.String(255), nullable=True, comment='头像URL')
    gender = db.Column(db.SmallInteger, nullable=True, comment='性别：0-未知，1-男，2-女')
    birth_year = db.Column(db.Integer, nullable=True, comment='出生年')
    birth_month = db.Column(db.Integer, nullable=True, comment='出生月')
    birth_day = db.Column(db.Integer, nullable=True, comment='出生日')
    birth_hour = db.Column(db.Integer, nullable=True, comment='出生时')
    register_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='注册时间')
    last_login_time = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-禁用，1-正常')
    is_deleted = db.Column(db.SmallInteger, nullable=False, default=0, comment='是否删除')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'phone': self.phone,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'gender': self.gender,
            'birth_year': self.birth_year,
            'birth_month': self.birth_month,
            'birth_day': self.birth_day,
            'birth_hour': self.birth_hour,
            'register_time': self.register_time.strftime('%Y-%m-%d %H:%M:%S') if self.register_time else None,
            'last_login_time': self.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if self.last_login_time else None,
            'status': self.status
        }


class UserWallet(db.Model):
    """用户钱包表"""
    __tablename__ = 'user_wallet'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='钱包ID')
    user_id = db.Column(db.BigInteger, db.ForeignKey('user.id'), nullable=False, comment='用户ID')
    balance = db.Column(db.Numeric(10, 2), nullable=False, default=0.00, comment='余额')
    total_recharge = db.Column(db.Numeric(10, 2), nullable=False, default=0.00, comment='总充值金额')
    total_consume = db.Column(db.Numeric(10, 2), nullable=False, default=0.00, comment='总消费金额')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-冻结，1-正常')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    user = db.relationship('User', backref=db.backref('wallet', uselist=False))

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'balance': float(self.balance),
            'total_recharge': float(self.total_recharge),
            'total_consume': float(self.total_consume),
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class UserVip(db.Model):
    """会员表"""
    __tablename__ = 'user_vip'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='会员ID')
    user_id = db.Column(db.BigInteger, db.ForeignKey('user.id'), nullable=False, comment='用户ID')
    vip_type = db.Column(db.SmallInteger, nullable=False, comment='会员类型：1-无限使用')
    start_time = db.Column(db.DateTime, nullable=False, comment='开始时间')
    expire_time = db.Column(db.DateTime, nullable=False, comment='到期时间')
    status = db.Column(db.SmallInteger, nullable=False, default=1, comment='状态：0-过期，1-有效')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    user = db.relationship('User', backref=db.backref('vip', uselist=False))

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'vip_type': self.vip_type,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'expire_time': self.expire_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }


class Order(db.Model):
    """订单表"""
    __tablename__ = 'order'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='订单ID')
    order_no = db.Column(db.String(32), unique=True, nullable=False, comment='订单编号')
    user_id = db.Column(db.BigInteger, db.ForeignKey('user.id'), nullable=False, comment='用户ID')
    product_type = db.Column(db.String(20), nullable=False, comment='产品类型：bazi_detail/character_detail/fengshui_detail/vip')
    product_id = db.Column(db.String(32), nullable=True, comment='产品ID')
    amount = db.Column(db.Numeric(10, 2), nullable=False, comment='订单金额')
    payment_type = db.Column(db.String(20), nullable=True, comment='支付方式：alipay/wechat')
    payment_time = db.Column(db.DateTime, nullable=True, comment='支付时间')
    status = db.Column(db.SmallInteger, nullable=False, default=0, comment='状态：0-未支付，1-已支付，2-已取消')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    user = db.relationship('User', backref=db.backref('orders', lazy='dynamic'))

    def to_dict(self):
        return {
            'id': self.id,
            'order_no': self.order_no,
            'user_id': self.user_id,
            'product_type': self.product_type,
            'product_id': self.product_id,
            'amount': float(self.amount),
            'payment_type': self.payment_type,
            'payment_time': self.payment_time.strftime('%Y-%m-%d %H:%M:%S') if self.payment_time else None,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }
